/**
 * 路由入口 
 */
import { computed } from 'vue'
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import { RoutesDataItem } from "@/routes";
import store from "@/store/index";
import request from '@/utils/request';
// import { setRouter } from '@/utils/AddRouters';
// import MainRoter from '@/routes/homeRoutes';

// const homeRoter = setRouter(MainRoter);
const pageRoutes: Array<RoutesDataItem> = [
  {
    title: 'empty',
    path: '/',
    name: 'login',
    component: () => import('@/views/user/user.vue')
  },
  {
    path: "/logout",
    name: "logout",
    redirect: { name: "login" },
    meta: {
      auth: true,
    },
  }
]


const router = createRouter({
  scrollBehavior(/* to, from, savedPosition */) {
    return { top: 0 }
  },
  history: createWebHashHistory(process.env.BASE_URL),//createWebHashHistory(process.env.BASE_URL),
  routes: pageRoutes as any,
});

/**
 * 
 * @param list 验证路由是否存在
 * @param route 
 * @returns 
 */
const testRouter = (list: any[], route: any): boolean => {
  let isExist = false
  for(const item of list){
    if (item.path === route.path) {
     return isExist = true
      
    }
    if (item.children && item.children.length > 0) {
      isExist = testRouter(item.children,route)
    }
  } 
  return isExist
}


/**
 * 使用时需要验证是否登录
 *  1、需要判断用户是否登录
 *  2、是否已获取过响应菜单
 */
router.beforeEach((to, from, next) => {
  if (store.getters["user/getMenus"].length > 0) {
    next()
  }

  // //判断用户是否登录
  // if (store.getters["user/getLoginStatus"] === 'ok') {
  //   if (store.getters["user/getMenus"].length > 0) {
  //     // 动态路由处理
  //     if (to.matched.length === 0) {
  //       // 匹配路由是否存在
  //       next({
  //         name: "404",
  //       });
  //     } else {
  //       next();
  //     }
  //   } else {
  //获取当前用户并添加路由
  store.dispatch("user/getUserInfo")
    .then((resp) => {
      if (resp) {
        resp.forEach((route: any) => {
          const isExist = testRouter(router.getRoutes(), route) 
          if (!isExist) {
            router.addRoute(route);
            router.options.routes.push(route);
          } 
        });
        console.log(router.options.routes)
        next({ ...to, replace: true });
      } else {
       return  next({
              path: '/login'
            })
      }
    
    })
    .catch((error) => {
      console.log(error);
    });
  // next();
 
  // }
  // } else {
  //    next({
  //     path: '/login'
  //   })
  // }

})



export default router;
